<template>
  <div class="file-upload">
    <el-upload
      ref="upload"
      :action="action"
      :accept="`${acceptType}/${subType}`"
      :file-list="originList"
      :before-upload="handleBeforeUpload"
      :on-change="handleChange"
      :headers="headers"
      list-type="picture-card">
      <i class="el-icon-plus"></i>
      <template slot="file" slot-scope="{file}" v-if="file.status === 'success'">
        <div class="upload-file-content">
          <img class="el-upload-list__item-thumbnail" :src="file.url" v-if="acceptType === 'image'">
          <video
            class="el-upload-list__item-thumbnail"
            v-if="acceptType === 'video' || acceptType === 'audio'"
            :src="file.url"
            :poster="acceptType === 'audio' ? require('./music.png') : ''"
          ></video>
          <label class="el-upload-list__item-status-label">
            <i class="el-icon-upload-success el-icon-check"></i>
          </label>
          <span class="el-upload-list__item-actions">
            <span class="el-upload-list__item-preview" @click="handlePicturePreview(file)" v-if="acceptType === 'image'">
              <i class="el-icon-zoom-in"></i>
            </span>
            <span class="el-upload-list__item-preview" @click="handleMediaPreview(file)"  v-if="acceptType === 'video' || acceptType === 'audio'">
              <i class="el-icon-video-play"></i>
            </span>
            <span class="el-upload-list__item-delete" @click="handleRemove(file)">
              <i class="el-icon-delete"></i>
            </span>
          </span>
        </div>
      </template>
    </el-upload>
    <el-dialog title="播放" :visible.sync="mediaDialogVisiable" width="500" top="5vh" append-to-body @close="mediaDialogClose">
      <video controls autoplay :src="mediaPlayUrl" width="100%" height="auto" ref="mediaPlayer"></video>
    </el-dialog>
  </div>
</template>
/* to do */
// readonly
// 压缩
<script>
import { getToken } from '@/utils/auth'

export default {
  props: {
    action: {
      type: String,
      default: '/api/file'
    },
    // image、video、audio
    acceptType: {
      type: String,
      default: 'video'
    },
    subType: {
      type: String,
      default: '*'
    },
    fileString: {
      type: String,
      default: ''
    },
    // 上传数量上限
    limit: {
      type: Number,
      default: 0
    },
    // 上传大小上限，MB
    size: {
      type: Number,
      default: 0
    },
    // 上传头部
    headers: {
      type: Object,
      default() {
        return {
          token: getToken()
        }
      }
    },
    value: {
      type: String,
      default: ''
    }
  },
  model: {
    prop: 'fileString',
    event: 'handleChange'
  },
  created() {
    this.handleFileListChange(this.fileList)
  },
  watch: {
    fileList(newList) {
      this.handleFileListChange(newList)
    }
  },
  computed: {
    fileList() {
      if (this.fileString) {
        return this.fileString.split('|')
      } else {
        return []
      }
    }
  },
  data() {
    return {
      originList: [],
      mediaDialogVisiable: false,
      mediaPlayUrl: ''
    }
  },
  methods: {
    handleFileListChange(fileList) {
      const newList = []
      for (const file of fileList) {
        if (!file) {
          throw Error('fileList格式错误！')
        }
        if (typeof file === 'string') {
          newList.push({ url: file })
        } else if (typeof file === 'object' && file.url) {
          newList.push(file)
        }
      }
      this.originList = newList
    },
    handleBeforeUpload(file) {
      if (this.size) {
        const fileSize = file.size / 1024 / 1024
        if (this.size < fileSize) {
          this.$message({ type: 'warning', message: `上传文件限制大小为：${this.size}MB` })
          return false
        }
      }
      if (this.limit) {
        const uploadFiles = this.$refs.upload.uploadFiles
        const length = uploadFiles.length
        if (this.limit < length) {
          this.$message({ type: 'warning', message: `上传文件最大数量为：${this.limit}个` })
          return false
        }
      }
    },
    handleRemove(file) {
      const index = this.$refs.upload.uploadFiles.findIndex(item => item === file)
      this.$refs.upload.uploadFiles.splice(index, 1)
      this.$emit('handleChange', this.getFileList().join('|'))
    },
    handlePicturePreview(file) {
      this.$createImgViewer({
        $props: {
          images: [file.url]
        }
      }).show()
    },
    handleMediaPreview(file) {
      this.mediaDialogVisiable = true
      this.mediaPlayUrl = file.url
    },
    mediaDialogClose() {
      if (this.$refs.mediaPlayer) {
        this.mediaPlayUrl = ''
      }
    },
    getFileList() {
      const uploadFiles = this.$refs.upload.uploadFiles.filter(item => item.status === 'success')
      return uploadFiles.map(item => {
        return item.response ? item.response.url : item.url
      })
    },
    handleChange() {
      this.$emit('handleChange', this.getFileList().join('|'))
    }
  }
}
</script>
<style lang="scss">
.file-upload {
  .el-upload-list--picture-card .el-progress {
    width: 76px;
    height: 76px;
    .el-progress-circle {
      width: 100% !important;
      height: 100% !important;
    }
  }
  .upload-file-content {
    height: 100%;
    img {
      height: 100%;
      width: 100%;
    }
    video {
      height: 100%;
      width: 100%;
      object-fit: fill;
    }
  }
}
</style>
